﻿using NLog;
using Scap.Core;
using Scap.Data;
using Scap.Info;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using zkemkeeper;

namespace Scap.App.Enroll
{
    public partial class ShellForm : Form
    {
        static Logger logger = LogManager.GetCurrentClassLogger();

        private bool bIsConnected;
        //Create Standalone SDK class dynamicly.
        public CZKEM axCZKEM1 = new CZKEM();
        private int iMachineNumber = 1;
        private int iCanSaveTmp = 0;
        private int _iFingerIndex;

        

        public ShellForm()
        {
            InitializeComponent();
            axCZKEM1.OnEnrollFingerEx += axCZKEM1_OnEnrollFingerEx;
            
        }



        void axCZKEM1_OnEnrollFingerEx(string EnrollNumber, int FingerIndex, int ActionResult, int TemplateLength)
        {
            if (ActionResult == 0)
                statusLabel.Text = "Enrolamiento exitoso";
            else
                statusLabel.Text = "Enrolamiento fallido";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            logger.Info("Loading devices...");
            DeviceHandler dHandler = new DeviceHandler();
            ScapDeviceCollection devices = dHandler.GetScapDevices();
            logger.Info("Loading devices...[OK]");

            logger.Info("Loading employees...");
            EmployeeHandler eHandler = new EmployeeHandler();
            ScapEmployeeCollection employees = eHandler.GetScapEmployees();
            employeeComboBox.DisplayMember = "FullName";
            employeeComboBox.ValueMember = "Id";
            employeeComboBox.DataSource = employees;
            logger.Info("Loading employees...[OK]");

            //devicesToolStripComboBox.ComboBox.DisplayMember = "Name";
            //devicesToolStripComboBox.ComboBox.ValueMember = "IpAddress";
            //devicesToolStripComboBox.ComboBox.DataSource = devices;

            InitializeSensor();
        }

        private void InitializeSensor()
        {
            statusLabel.Text = "Inicializando sensor...";
            logger.Info("Connecting sensor...");

            //axZKFPEngX1.EndEngine();

            if (axZKFPEngX1.InitEngine() == 0)
            {

                axZKFPEngX1.FPEngineVersion = "9";

                logger.Info("Sensor count: " + axZKFPEngX1.SensorCount);
                logger.Info("Sensor index: " + axZKFPEngX1.SensorIndex);
                logger.Info("Sensor SN: " + axZKFPEngX1.SensorSN);
                axZKFPEngX1.EnrollCount = 3;
                statusLabel.Text = "Inicializando sensor...[OK]";
                logger.Info("Connecting sensor...[OK]");
            }
            else
            {
                statusLabel.Text = "Inicializando sensor...[ERROR]";
                logger.Error("Failed to connecting sensor");
            }
        }

        private void connectToolStripButton_Click(object sender, EventArgs e)
        {
            //Cursor = Cursors.WaitCursor;
            //ScapDevice dev = devicesToolStripComboBox.SelectedItem as ScapDevice;

            //if (dev == null)
            //{
            //    ShowWarning("Please select a device");
            //    return;
            //}

            //if (string.IsNullOrEmpty(dev.IpAddress) || dev.IpPort == 0)
            //{
            //    ShowWarning("IP and Port cannot be null");
            //    return;
            //}

            //int idwErrorCode = 0;
                   
            //bIsConnected = axCZKEM1.Connect_Net(dev.IpAddress, dev.IpPort);

            //if (bIsConnected == true)
            //{

            //    generalToolStripStatusLabel.Text = "Current State:Connected";
            //    iMachineNumber = 1;//In fact,when you are using the tcp/ip communication,this parameter will be ignored,that is any integer will all right.Here we use 1.
            //    axCZKEM1.RegEvent(iMachineNumber, 65535);//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
            //}
            //else
            //{
            //    axCZKEM1.GetLastError(ref idwErrorCode);
            //    ShowError("Unable to connect the device,ErrorCode=" + idwErrorCode.ToString());
            //}

            //Cursor = Cursors.Default;
        }

     

        private void disconnectToolStripButton_Click(object sender, EventArgs e)
        {
            //Cursor = Cursors.WaitCursor;

            //if (bIsConnected)
            //{
            //    axCZKEM1.Disconnect();
            //    bIsConnected = false;               
            //    generalToolStripStatusLabel.Text = "Current State:DisConnected";
               
            //}

            //Cursor = Cursors.Default;
        }

        private void ShowError(string msg)
        {
            MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private static void ShowWarning(string msg)
        {
            MessageBox.Show(msg, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        Button b;
        private void fingerButton_Click(object sender, EventArgs e)
        {

            if (b != null && b.BackColor == Color.LightGreen  && b == sender)
            {
                b.BackColor = Color.Lavender;
                statusLabel.Text = "Registro de huella cancelado";
                return;
            }

            if (b != null)
                b.BackColor = Color.Lavender;

          

            b = sender as Button;
            b.BackColor = Color.LightGreen;

            
            statusLabel.Text = "Inicie registro de huella";
            fingerPictureBox.Image = null;
            Enroll(int.Parse(b.Tag.ToString()));
        }
      
        private void Enroll(int iFingerIndex)
        {
            _iFingerIndex = iFingerIndex;

            axZKFPEngX1.CancelEnroll();
            axZKFPEngX1.EnrollCount = 3;
            axZKFPEngX1.BeginEnroll();


            //ScapEmployee employee = employeeComboBox.SelectedItem as ScapEmployee;
            //int iUserID = employee.Id;
            //int iFlag = 0;

            //if (bIsConnected == false)
            //{
            //    ShowWarning("Please connect the device first!");
            //    return;
            //}

            //if (iUserID == 0)
            //{
            //    ShowWarning("UserID must be inputted first!");
            //    return;
            //}

            //int idwErrorCode = 0;
            //axCZKEM1.CancelOperation();
            ////If the specified index of user's templates has existed ,delete it first.(SSR_DelUserTmp is also available sometimes)
            //axCZKEM1.SSR_DelUserTmpExt(iMachineNumber, iUserID.ToString(), iFingerIndex);

            //if (axCZKEM1.StartEnrollEx(iUserID.ToString(), iFingerIndex, iFlag))
            //{
            //    statusLabel.Text = "Inicializando enrolamiento...";
               
            //    iCanSaveTmp = 1;
            //    //After enrolling templates,you should let the device into the 1:N verification condition
            //    axCZKEM1.StartIdentify();
            //}
            //else
            //{
            //    axCZKEM1.GetLastError(ref idwErrorCode);
            //    ShowError("Operation failed,ErrorCode=" + idwErrorCode.ToString());
            //}
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            //if (bIsConnected == false)
            //{
            //    ShowWarning("Please connect the device first!");
            //    return;
            //}

            //if (iCanSaveTmp == 0)//You haven't enrolled the templates.
            //{
            //    ShowWarning("Please enroll the fingerprint templates first!");
            //    return;
            //}


            //ScapEmployee employee = employeesToolStripComboBox.SelectedItem as ScapEmployee;

            //int idwFingerIndex = 0;
            //int iTmpLength = 0;
            //string sdwEnrollNumber = employee.Id.ToString();
            //int iFlag = 0;
            //byte[] byTmpData = new byte[2000];//modify by darcy on Dec.9 2009
            //string sName = "";
            //string sPassword = "";
            //int iPrivilege = 0;
            //bool bEnabled = false;

            //axCZKEM1.EnableDevice(iMachineNumber, false);
            //Cursor = Cursors.WaitCursor;
            //axCZKEM1.ReadAllTemplate(iMachineNumber);

            //while (axCZKEM1.SSR_GetUserInfo(iMachineNumber, sdwEnrollNumber, out sName, out sPassword, out iPrivilege, out bEnabled))
            //{
            //    if (axCZKEM1.GetUserTmpEx(iMachineNumber, sdwEnrollNumber, idwFingerIndex, out iFlag, out byTmpData[0], out iTmpLength))
            //    {
                    
                   
            //    }
            //    else
            //    {
            //        ShowError("Saving templates to database failed !");
            //    }
            //}

            //axCZKEM1.RefreshData(iMachineNumber);//the data in the device should be refreshed
            //axCZKEM1.EnableDevice(iMachineNumber, true);
            //Cursor = Cursors.Default;
            //MessageBox.Show("Successfully save templates to database ! ", "Success");
        }

        private void axZKFPEngX1_OnImageReceived(object sender, AxZKFPEngXControl.IZKFPEngXEvents_OnImageReceivedEvent e)
        {
            Graphics g = fingerPictureBox.CreateGraphics();
            Bitmap bmp = new Bitmap(fingerPictureBox.Width, fingerPictureBox.Height);
            g = Graphics.FromImage(bmp);
            int dc = g.GetHdc().ToInt32();
            axZKFPEngX1.PrintImageAt(dc, 0, 0, bmp.Width, bmp.Height);
            g.Dispose();
            fingerPictureBox.Image = bmp;
        }

        private void axZKFPEngX1_OnFeatureInfo(object sender, AxZKFPEngXControl.IZKFPEngXEvents_OnFeatureInfoEvent e)
        {
            String strTemp = "Calidad de la huella:";
            
            if (e.aQuality != 0)
            {
                strTemp = strTemp + " mala";
            }
            else
            {
                strTemp = strTemp + " buena";
            }

            if (axZKFPEngX1.IsRegister)
            {
                if (axZKFPEngX1.EnrollIndex - 1 > 0)
                {
                    strTemp = strTemp + ", presione su dedo " + Convert.ToString(axZKFPEngX1.EnrollIndex - 1) + " veces más!";
                }
              
            }

            statusLabel.Text = strTemp;
            logger.Info(strTemp);
        }

        private void axZKFPEngX1_OnEnroll(object sender, AxZKFPEngXControl.IZKFPEngXEvents_OnEnrollEvent e)
        {
            if (e.actionResult)
            {

                string temp = axZKFPEngX1.GetTemplateAsStringEx("9");
                // save it
                ScapEmployee employee = employeeComboBox.SelectedItem as ScapEmployee;
                ScapEmployeeEnroll enroll = new ScapEmployeeEnroll();
                enroll.Data = (byte[])e.aTemplate;
                enroll.DataStr = temp;
                enroll.Index = _iFingerIndex;
                enroll.Type = EnrollType.Fingerprint;
                EmployeeHandler eHandler = new EmployeeHandler();
                eHandler.Save(employee, enroll);

                statusLabel.Text = "Huella registrada!";
            }
            else
            {
                statusLabel.Text = "Huella no registrada!";
            }
        }

       


    }
}
